package com.greatwqs.wmall.product.provider.manager.impl;

import com.greatwqs.wmall.common.module.exception.AppException;
import com.greatwqs.wmall.common.module.exception.ErrorCode;
import com.greatwqs.wmall.product.provider.manager.ProductManager;
import com.greatwqs.wmall.product.provider.mapper.ProductMapper;
import com.greatwqs.wmall.product.provider.model.po.Product;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wang-qingsong
 * @description User 通用功能实现
 */
@Slf4j
@Component
public class ProductManagerImpl implements ProductManager {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Product getProductById(Long productId) {
        return productMapper.selectByProductId(productId);
    }

    @Override
    public Product getProductByIdNotNull(Long productId) {
        Product product = productMapper.selectByProductId(productId);
        if (product == null) {
            log.warn("Product not found, productId: {}", productId);
            throw new AppException(ErrorCode.PRODUCT_NOT_FOUND);
        }
        return product;
    }

    @Override
    public List<Product> getProductListByIds(List<Long> productIds) {
        if (CollectionUtils.isEmpty(productIds)) {
            return List.of();
        }
        return productMapper.selectListByProductIds(productIds);
    }

    @Override
    public Map<Long, Product> getProductMapByIds(List<Long> productIds) {
        return getProductListByIds(productIds).stream()
                .collect(Collectors.toMap(Product::getProductId, product -> product));
    }
}
